package server;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.ssl.*;
import msgs.*;
/**
 * Pops admin messages off the outgoing queue and sends them out to the appropriate client
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class AdminSender extends Thread implements TTConstants {
	//private SSLSocket sock;
	private Socket sock;
	private int port;
	private boolean go;
	
	/**
	 * The outgoing msg queue
	 */
	protected static Vector<AdminMsg> outQ;
	
	private AdminMsg amsg;
	private ObjectOutputStream oos;
	//private final static String TS_PATH = "servers.jks"; // trusted servers
	//private final static String TS_PASS = "changeit";
	//final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
	
	public AdminSender(int port) {
		this.port = port;
		outQ = new Vector<AdminMsg>();
		go = true;
		//System.setProperty("javax.net.ssl.trustStore", TS_PATH);
		//System.setProperty("javax.net.ssl.trustStorePassword", TS_PASS);
	}
	public void run() {
		while (go) {
			if (!(outQ.isEmpty())) {
				// pop a message off, if we have one
				amsg = outQ.remove(0);
				try {
					//SSLSocketFactory factory =
						//(SSLSocketFactory) SSLSocketFactory.getDefault();
					//sock = (SSLSocket)factory.createSocket(amsg.getIP(), port);
					//sock.setEnabledCipherSuites(enabledCipherSuites);
					System.out.println(amsg.getIP());	// leaving for debugging tonight
					sock = new Socket(amsg.getIP(), port);
					//write the object out
					oos = new ObjectOutputStream(sock.getOutputStream());
					oos.writeObject(amsg);
					oos.flush();
					oos.close();
					sock.close();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
			else {
				//sleep if we have nothing to do
				try { Thread.sleep(100); }
				catch (InterruptedException e) { e.printStackTrace(); }
			}
		}
	}
	
	public void killAdminSender() {
		go = false;
	}
}
